<template>
  <div class="fruit-container">
    <div class="page-header">
      <h1>🍊 Fruit Inventory Management</h1>
      <el-button type="primary" :icon="Plus" @click="showAddDialog">Add Fruit</el-button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input 
        v-model="searchText" 
        placeholder="Search fruit name..." 
        :prefix-icon="Search"
        style="width: 300px"
        clearable
        @clear="handleSearch"
        @keyup.enter="handleSearch"
      />
      <el-button type="primary" :icon="Search" @click="handleSearch" style="margin-left: 10px">
        Search
      </el-button>
      <el-button @click="resetSearch">Reset</el-button>
    </div>

    <!-- 水果列表 -->
    <el-table 
      v-loading="loading"
      :data="fruits" 
      style="width: 100%" 
      stripe
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="Fruit Name" width="150" />
      <el-table-column prop="category" label="Category" width="150" />
      <el-table-column prop="price" label="Price" width="120">
        <template #default="scope">
          ${{ Number(scope.row.price).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="total_stock" label="Total Stock" width="120" />
      <el-table-column prop="stock" label="Available" width="120">
        <template #default="scope">
          <span :style="{ color: scope.row.stock < 50 ? '#f56c6c' : '#67c23a' }">
            {{ scope.row.stock }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="Warehouses" width="300">
        <template #default="scope">
          <div v-if="scope.row.warehouses && scope.row.warehouses.length > 0">
            <el-tag 
              v-for="wh in scope.row.warehouses" 
              :key="wh.id" 
              size="small"
              style="margin: 2px"
            >
              {{ wh.name }} ({{ wh.FruitWarehouse.quantity }})
            </el-tag>
          </div>
          <span v-else style="color: #999">No warehouse</span>
        </template>
      </el-table-column>
      <el-table-column label="Status" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.stock > 50 ? 'success' : scope.row.stock > 20 ? 'warning' : 'danger'">
            {{ scope.row.stock > 50 ? 'Sufficient' : scope.row.stock > 20 ? 'Low' : 'Critical' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Operations" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" type="primary" :icon="Edit" @click="handleEdit(scope.row)">
            Edit
          </el-button>
          <el-button size="small" type="danger" :icon="Delete" @click="handleDelete(scope.row)">
            Delete
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空状态 -->
    <el-empty v-if="!loading && fruits.length === 0" description="No fruit data" />

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="600px"
      @close="resetForm"
    >
      <el-form 
        ref="formRef"
        :model="form" 
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="Fruit Name" prop="name">
          <el-input v-model="form.name" placeholder="Please enter fruit name" />
        </el-form-item>
        <el-form-item label="Category" prop="category">
          <el-select v-model="form.category" placeholder="Please select category" style="width: 100%">
            <el-option 
              v-for="cat in categories" 
              :key="cat.id" 
              :label="cat.name" 
              :value="cat.name"
            >
              <span>{{ cat.icon }} {{ cat.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="Price" prop="price">
          <el-input-number 
            v-model="form.price" 
            :min="0"
            :precision="2" 
            :step="0.1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="Total Stock" prop="total_stock">
          <el-input-number 
            v-model="form.total_stock" 
            :min="0"
            style="width: 100%"
          />
          <div style="color: #909399; font-size: 12px; margin-top: 5px">
            Total stock quantity (allocation to warehouses can be done in the warehouse details page)
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="handleSave" :loading="saveLoading">Confirm</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Edit, Delete, Search } from '@element-plus/icons-vue';
import { fruitAPI, categoryAPI } from '@/api';

const searchText = ref('');
const fruits = ref([]);
const categories = ref([]);
const loading = ref(false);
const saveLoading = ref(false);

const dialogVisible = ref(false);
const dialogTitle = ref('Add Fruit');
const formRef = ref(null);
const isEdit = ref(false);
const editId = ref(null);

const form = ref({
  name: '',
  category: '',
  price: 0,
  total_stock: 0
});

const formRules = {
  name: [
    { required: true, message: 'Please enter fruit name', trigger: 'blur' }
  ],
  category: [
    { required: true, message: 'Please select category', trigger: 'change' }
  ],
  price: [
    { required: true, message: 'Please enter price', trigger: 'blur' }
  ],
  total_stock: [
    { required: true, message: 'Please enter total stock', trigger: 'blur' }
  ]
};

// 加载分类列表
const loadCategories = async () => {
  try {
    const response = await categoryAPI.getList();
    if (response.success) {
      categories.value = response.data;
    }
  } catch (error) {
    console.error('Load categories failed:', error);
  }
};

// 加载水果列表
const loadFruits = async (search = '') => {
  loading.value = true;
  try {
    const params = search ? { search } : {};
    const response = await fruitAPI.getList(params);
    
    if (response.success) {
      fruits.value = response.data;
    }
  } catch (error) {
    console.error('Load fruits failed:', error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  loadFruits(searchText.value);
};

// 重置搜索
const resetSearch = () => {
  searchText.value = '';
  loadFruits();
};

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = 'Add Fruit';
  isEdit.value = false;
  editId.value = null;
  resetForm();
  dialogVisible.value = true;
};

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = 'Edit Fruit';
  isEdit.value = true;
  editId.value = row.id;
  
  form.value = {
    name: row.name,
    category: row.category,
    price: Number(row.price),
    total_stock: row.total_stock
  };
  dialogVisible.value = true;
};

// 保存
const handleSave = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return;
    
    saveLoading.value = true;
    try {
      let response;
      
      if (isEdit.value) {
        // 更新
        response = await fruitAPI.update(editId.value, form.value);
      } else {
        // 创建
        response = await fruitAPI.create(form.value);
      }
      
      if (response.success) {
        ElMessage.success(response.message || 'Saved successfully');
        dialogVisible.value = false;
        loadFruits(searchText.value);
      }
    } catch (error) {
      console.error('Save failed:', error);
      const errorMessage = error.response?.data?.message || error.message || 'Save failed';
      ElMessage.error(errorMessage);
    } finally {
      saveLoading.value = false;
    }
  });
};

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `Are you sure you want to delete "${row.name}"?`, 
    'Confirm', 
    {
      confirmButtonText: 'Confirm',
      cancelButtonText: 'Cancel',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await fruitAPI.delete(row.id);
      
      if (response.success) {
        ElMessage.success(`"${row.name}" deleted successfully`);
        loadFruits(searchText.value);
      }
    } catch (error) {
      console.error('Delete failed:', error);
    }
  }).catch(() => {
    // 用户取消
  });
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  form.value = {
    name: '',
    category: '',
    price: 0,
    total_stock: 0
  };
};

// 页面加载时获取数据
onMounted(() => {
  loadFruits();
  loadCategories();
});
</script>

<style scoped>
.fruit-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 28px;
  color: #333;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}
</style>
